#include "channel.h"

float xSpacing = 10.0f;
float ySpacing = 10.0f;
float plotBase = 0.0f;
float defaultPlotBase = 0.0f;

//! Channel constructor.
channel::channel() 
{
    active = false;
    enabled = true;
    plotIndex = 0;
    plotOrigin = 0;
    plot.setPrimitiveType(sf::LinesStrip);
}

//! Gets the minimum value of the variable.
float channel::chanMin()
{
    float min = std::numeric_limits<float>::max();
    for (int i = 0; i < rawValues.size(); ++i)
    {
        min = rawValues[i] < min ? rawValues[i] : min;
    }
    return min;
}

//! Gets the maximum value of the variable.
float channel::chanMax()
{
    float max = 0;
    for (int i = 0; i < rawValues.size(); ++i)
    {
        max = rawValues[i] > max ? rawValues[i] : max;
    }
    return max;
}

//! Gets the average value of the variable.
float channel::chanAverage()
{
    float total = 0;
    for (int i = 0; i < rawValues.size(); ++i)
    {
        total += rawValues[i];
    }
    return total / rawValues.size();
}

//! Converts values from the serial buffer into vertex arrays.
void channel::drawPlot(sf::RenderWindow &window, sf::Vector2i mousePosition, std::string buffer, int plotMultiplier)
{
    float plotPosition = 0;
    plot.resize(plot.getVertexCount() + 1);
    
    try
    {
        rawValues.push_back(std::stof(buffer));
    }
    catch(const std::exception &e)
    {
        rawValues.push_back(0.0);
    }

    for (int i = 0; i < plotIndex; ++i)
    {
        plot[i].position = sf::Vector2f(plotOrigin + (i * xSpacing), plot[i].position.y);
        plot[i].color = color;
    }

    for (int i = plotIndex; i < plot.getVertexCount(); ++i)
    {
        try
        {
            plotPosition = (std::stof(buffer) * ySpacing) / plotMultiplier;
        }
        catch(const std::exception &e)
        {
            plotPosition = 0;
        }
        
        plot[i].position = sf::Vector2f(plotOrigin + (plotIndex * xSpacing), plotBase - (plotPosition));
        plot[i].color = color;
    }

    plotIndex++;

    while (plotOrigin + (plotIndex * xSpacing) >= window.getView().getSize().x)
    {
        plotOrigin--;
    }
    
    while (plotOrigin + (plotIndex * xSpacing) < 0)
    {
        plotOrigin++;
    }
}

//! Redraws the vertex array.
void channel::redrawPlot()
{
    for (int i = 0; i < plot.getVertexCount(); ++i)
    {
        plot[i].position = sf::Vector2f(plotOrigin + (i * xSpacing), plot[i].position.y);
        plot[i].color = color;
    }
}